const fs = require('fs-extra');
const packages = fs.readJSONSync('./exposes/config.json');

const targetFolder = './desk/extensions';
const fromFolder = './dist';

const getEntryContent = () => {
  const entryFile = './dist/remoteEntry.js';
  let fileContent = fs.readFileSync(entryFile).toString();

  /******/
  fileContent = fileContent.replace(/\/\*([*]+)\*\//g, '');
  fileContent = fileContent.replace(/\/\*!([*]+)!\*\\/g, '');
  fileContent = fileContent.replace(/!\*\*(.*)\*\*!/g, '');
  fileContent = fileContent.replace(/\\\*([*]+)\*\//g, '');
  fileContent = fileContent.replace(/\/\*(.*)\*\//g, '');

  // 删除双横杠注释
  fileContent = fileContent.replace(/\/\/ (.*)\r\n/g, '');
  fileContent = fileContent.replace(/\/\/ (.*)\r/g, '');
  fileContent = fileContent.replace(/\/\/ (.*)\n/g, '');

  // 删除换行和空格
  fileContent = fileContent.replace(/\r\n/g, '');
  fileContent = fileContent.replace(/\s+/g, ' ');

  return fileContent;
};


const mapJSFiles = () => {
  const fileContent = getEntryContent();
  const key = './route';
  const name = packages.exposes[key].name;
  // // 创建文件目录
  fs.emptyDirSync(targetFolder + '/' + name);
  createDirectoryIfNotExist(targetFolder, [name]);
  createDirectoryIfNotExist(targetFolder, [name, 'js']);
  createDirectoryIfNotExist(targetFolder, [name, 'img']);
  createDirectoryIfNotExist(targetFolder, [name, 'css']);

  fs.copySync(fromFolder + '/js', targetFolder + '/' + name + '/js');
  if (isDirectory(fromFolder + '/img')) {
    fs.copySync(fromFolder + '/img', targetFolder + '/' + name + '/img');
  }
  if (isDirectory(fromFolder + '/css')) {
    fs.copySync(fromFolder + '/css', targetFolder + '/' + name + '/css');
  }
  const content = fileContent.replace(/\/\/#.+/g, '');
  fs.writeFileSync(targetFolder + '/' + name + '/index.js', content);
};


// -------------文件操作相关-------------//

/**
 * 检查目标目录是否存在，不存在则创建
 *
 * @param {*} dst // 目标目录
 * @param {*} childFolder // 子目录数组
 */
function createDirectoryIfNotExist (dst, childFolder = []) {
  if (dst === '') {
    return;
  }
  if (isDirectory(dst)) {
    let targetDir = dst;
    childFolder.forEach((child) => {
      targetDir += '/' + child;
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir);
      }
    });
    return;
  }
  const dstArray = dst.split('/');
  const parent = dstArray.slice(0, dstArray.length - 1).join('/');
  const child = dstArray.slice(dstArray.length - 1);
  childFolder.unshift(child);

  createDirectoryIfNotExist(parent, childFolder);
}

/**
 * 判断路径是否为目录
 * @param {string} dir
 */
function isDirectory (dir) {
  try {
    const stats = fs.statSync(dir);
    return stats.isDirectory();
  } catch (e) {
    return false;
  }
}

// 执行
(() => {
  mapJSFiles();
})();
